package com.simp.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simp.costant.Constant;
import com.simp.dto.SysThemeDto;
import com.simp.entity.SysThemeEntity;
import com.simp.entity.SysUserEntity;
import com.simp.expection.GlobalException;
import com.simp.mapper.SysThemeMapper;
import com.simp.page.PageVO;
import com.simp.page.R;
import com.simp.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author pan.shun
 * @since 2022/3/15 11:06
 */
@Slf4j
@Service
public class SysThemeService extends ServiceImpl<SysThemeMapper, SysThemeEntity> {

    @Autowired
    private SysUserService sysUserService;

    public R getThemeByUserId(HttpServletRequest request) {
        SysUserEntity user;
        try {
            user = sysUserService.getById(JwtUtil.getJwtClaimsDetailByRequest(request).getUserId());
        } catch (Exception e) {
            return R.loginError();
        }
        if (null == user) {
            return R.loginError();
        } else {
            String themeId = user.getThemeId();
            if (!StringUtils.isEmpty(themeId)) {
                SysThemeEntity sysThemeEntity = this.getById(themeId);
                sysThemeEntity.setUserHead(user.getUserHead());
                log.info("当前用户已经设置了主题,主题信息 :{}", sysThemeEntity);
                return R.success(sysThemeEntity);
            } else {
                log.info("当前用户暂未设置主题,返回主题信息为空");
                JSONObject obj = new JSONObject();
                obj.put("userHead", user.getUserHead());
                return R.success(obj);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public R addOrUpdateTheme(SysThemeEntity sysThemeEntity) {
        if (!StringUtils.isEmpty(sysThemeEntity.getId())) {
            this.updateById(sysThemeEntity);
            if (!StringUtils.isEmpty(sysThemeEntity.getUserId())) {
                SysUserEntity sysUserEntity = sysUserService.getById(sysThemeEntity.getUserId());
                sysUserEntity.setThemeId(sysThemeEntity.getId());
                sysUserService.updateById(sysUserEntity);
            }
        } else {
            this.save(sysThemeEntity);
            if (!StringUtils.isEmpty(sysThemeEntity.getUserId())) {
                SysUserEntity sysUserEntity = sysUserService.getById(sysThemeEntity.getUserId());
                sysUserEntity.setThemeId(sysThemeEntity.getId());
                sysUserService.updateById(sysUserEntity);
            }
        }
        return R.success();
    }

    public R getThemeList() {
        LambdaQueryWrapper<SysThemeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysThemeEntity::getId, SysThemeEntity::getName);
        List<SysThemeEntity> list = this.list(queryWrapper);
        return R.success(list);
    }

    public R getThemeById(String id) {
        SysThemeEntity theme = this.getById(id);
        if (null == theme) {
            throw new GlobalException("主题不存在");
        } else {
            return R.success(theme);
        }
    }

    public PageVO<SysThemeEntity> getThemePageList(HttpServletRequest request, SysThemeDto sysThemeDto) {
        LambdaQueryWrapper<SysThemeEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(sysThemeDto.getName())) {
            queryWrapper.like(SysThemeEntity::getName, sysThemeDto.getName());
        }
        Page<SysThemeEntity> iPage = this.page(new Page<>(sysThemeDto.getCurrent(), sysThemeDto.getSize()), queryWrapper);

        List<SysThemeEntity> records = iPage.getRecords();

        if (!CollectionUtils.isEmpty(records)) {
            String userId = JwtUtil.getJwtClaimsDetailByRequest(request).getUserId();
            SysUserEntity user = sysUserService.getById(userId);
            records.forEach(r -> {
                if (r.getId().equals(user.getThemeId())) {
                    r.setDefaultStatus(Constant.DEFAULT_THEME.DEFAULT);
                } else {
                    r.setDefaultStatus(Constant.DEFAULT_THEME.NOT_DEFAULT);
                }
            });
        }
        return new PageVO<>(iPage);
    }

    public R updateCurrentUserTheme(HttpServletRequest request, String themeId) {
        if (StringUtils.isEmpty(themeId)) {
            throw new GlobalException("主题ID不能为空");
        }
        String userId = JwtUtil.getJwtClaimsDetailByRequest(request).getUserId();
        SysUserEntity user = sysUserService.getById(userId);
        user.setThemeId(themeId);
        sysUserService.updateById(user);
        SysThemeEntity sysThemeEntity = this.getById(themeId);
        return R.success(sysThemeEntity);
    }

    public R removeThemeById(String id) {
        this.removeById(id);
        UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("theme_id", null);
        updateWrapper.eq("theme_id", id);
        sysUserService.update(updateWrapper);
        return R.success();
    }
}
